<script setup lang="ts">
import { tableBorder } from "@/utils/border/table-border.ts";
import { onMounted, reactive, ref, computed } from "vue";
import { downLoad, roleDeleteApi, roleListApi } from "@/services/roleApi.ts";
import { Message, PaginationProps } from "@arco-design/web-vue";
import type { RoleListType } from "@/types/RoleType.ts";
import RoleForm from "@/pages/system/Role/role-form.vue";
import useModal from "@/hooks/useModal.ts";
import { roleUpload } from "@/services/commonApi";
import { downloadFile } from "@/utils";
import RoleAssign from "@/pages/system/Role/role-assign.vue";
import RoleAuth from "@/pages/system/Role/role-auth.vue";
import { useRouter } from "vue-router";
import RoleDefaultHome from "@/pages/system/Role/role-default-home.vue";
import { shouldShowOperateColumn } from "@/directives/showColumn";
const formRef = ref<{
  init: () => void;
  edit: (row: RoleListType) => void;
}>();

const assignRef = ref<{
  init: (roleId: string) => void;
}>();

const authRef = ref<{
  init: (roleId: string) => void;
}>();

const home = ref<{
  init: (row: RoleListType) => void;
}>();

const { ModalShow, ModalHide } = useModal();

const router = useRouter();

const formSearch = reactive({
  roleName: "",
  roleCode: "",
  current: 1,
  size: 10,
});

const pagination = reactive<PaginationProps>({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
});

const data = ref<RoleListType[]>([]);

function queryData() {
  roleListApi(formSearch).then((res) => {
    if (res.code === 200) {
      data.value = res.data.records;
      pagination.total = res.data.total;
      pagination.current = res.data.current;
      pagination.pageSize = res.data.size;
    }
  });
}
// 分页
const handlePageChange = (page: number) => {
  formSearch.current = page;
  queryData();
};
// 添加
const handleAdd = () => {
  formRef.value?.init();
};
// 编辑
const handleEdit = (row: RoleListType) => {
  formRef.value?.edit(row);
};
// 删除
const handleDelete = (row: RoleListType) => {
  ModalShow({
    title: "提示",
    content: "您确认要删除这条角色吗？",
  }).then(() => {
    roleDeleteApi({
      id: row.id,
    }).then((res) => {
      if (res.code === 200) {
        Message.success(res.data);
        if (data.value.length === 1) {
          formSearch.current = formSearch.current - 1;
        }
        queryData();
        ModalHide();
      } else {
        ModalHide();
      }
    });
  });
};
// 用户
const handleAssign = (row: RoleListType) => {
  assignRef.value?.init(row.id);
};
// 授权
const handleAuth = (row: RoleListType) => {
  authRef.value?.init(row.id);
};
// 默认首页
const handleHome = (row: RoleListType) => {
  home.value?.init(row);
};
// 更多
const handleSelect = (e: string, row: RoleListType) => {
  if (e === "删除") {
    handleDelete(row);
  }
  if (e === "用户") {
    handleAssign(row);
  }
  if (e === "授权") {
    handleAuth(row);
  }
  if (e === "默认首页") {
    handleHome(row);
  }
};

onMounted(() => {
  queryData();
});

const columns = [
  {
    title: "序号",
    dataIndex: "index",
    align: "center",
    slotName: "index",
  },
  {
    title: "角色名称",
    dataIndex: "roleName",
    align: "center",
  },
  {
    title: "角色编码",
    dataIndex: "roleCode",
    align: "center",
  },
  {
    title: "描述",
    dataIndex: "description",
    align: "center",
  },
];

const dynamicColumns = computed(() => {
  /*if (
    shouldShowOperateColumn(
      ["edit", "delete", "user", "homepage", "authorization"],
      5
    )
  ) {
    return [
      ...columns,
      {
        title: "操作",
        slotName: "operate",
        align: "center",
        width: 150,
      },
    ];
  } else {
    return columns;
  }*/
  return [
    ...columns,
    {
      title: "操作",
      slotName: "operate",
      align: "center",
      width: 150,
    },
  ];
});

// 导出
const exportToExcel = () => {
  roleUpload(formSearch).then((res) => {
    downloadFile(res, `角色管理.xlsx`);
  });
};
const search = () => {
  formSearch.current = 1;
  queryData();
};
// 重置
const handleReset = () => {
  formSearch.roleName = "";
  formSearch.roleCode = "";
  search();
};

// 下载导入模版
const dowmLoad = () => {
  downLoad({ templateName: "roleTemplate" }).then((res) => {
    downloadFile(res as Blob, `角色导入模版.xlsx`);
  });
};
// 授权完成
const handleAuthList = () => {
  router.go(0);
};
</script>

<template>
  <a-space
    class="container"
    direction="vertical"
  >
    <a-card>
      <a-form
        label-align="left"
        auto-label-width
      >
        <a-row :gutter="24">
          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
          >
            <a-form-item label="角色名称">
              <a-input
                allow-clear
                placeholder="请输入角色名称"
                v-model="formSearch.roleName"
              />
            </a-form-item>
          </a-col>

          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
          >
            <a-form-item label="角色编码">
              <a-input
                allow-clear
                placeholder="请输入角色编码"
                v-model="formSearch.roleCode"
              />
            </a-form-item>
          </a-col>

          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
          >
            <a-space>
              <a-button
                type="primary"
                @click="search"
              >
                <template #icon>
                  <icon-search />
                </template>
                <span>查询</span>
              </a-button>
              <a-button @click="handleReset">
                <template #icon>
                  <icon-refresh />
                </template>
                <span>重置</span>
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <div class="tabletools">
        <a-space>
          <a-button
            type="primary"
            @click="handleAdd"
            v-has="'add'"
          >
            <template #icon>
              <icon-plus />
            </template>
            <span>新增</span>
          </a-button>

          <a-button
            type="primary"
            status="success"
            @click="exportToExcel"
            v-has="'export'"
          >
            <template #icon>
              <icon-share-external />
            </template>
            <span>导出</span>
          </a-button>

          <a-button
            type="primary"
            status="warning"
            @click="dowmLoad"
            v-has="'download'"
          >
            <template #icon>
              <icon-download />
            </template>
            下载导入模版
          </a-button>

          <ExcelUpload
            actions="role/importXls"
            @success="queryData"
            v-has="'import'"
          >导入</ExcelUpload>

        </a-space>
      </div>
      <a-table
        style="user-select: none;"
        :data="data"
        :columns="dynamicColumns"
        :bordered="tableBorder"
        :pagination="pagination"
        @page-change="handlePageChange"
      >

        <template #index="{record, column, rowIndex}">
          {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
        </template>

        <template #operate="{ record }">
          <a-space>
            <a-button
              type="primary"
              @click="handleEdit(record)"
              v-has="'edit'"
            >编辑</a-button>

            <a-dropdown @select="(e: string) => handleSelect(e, record)">
              <a-button
                type="primary"
                status="warning"
                v-more="{
                  list: ['delete', 'user', 'homepage','authorization'],
                  len: 4
                }"
              >
                <span>更多</span>
                <icon-down />
              </a-button>
              <template #content>
                <a-doption v-has="'delete'">删除</a-doption>
                <a-doption v-has="'user'">用户</a-doption>
                <a-doption v-has="'authorization'">授权</a-doption>
                <a-doption v-has="'homepage'">默认首页</a-doption>
              </template>
            </a-dropdown>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <role-form
      ref="formRef"
      @list="queryData"
    />
    <role-assign
      ref="assignRef"
      @list="queryData"
    />
    <role-auth
      ref="authRef"
      @list="handleAuthList"
    />
    <role-default-home
      ref="home"
      @list="queryData"
    />
  </a-space>
</template>

<style scoped lang="scss">
:deep(.arco-dropdown-open) {
  .arco-icon-down {
    transform: rotate(180deg);
  }
}
</style>